﻿/* $RCSFile: AddonNiceUser.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Authentication/AddonNiceUser.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:27  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using System.Globalization;

using AddonNice.Configuration;
using AddonNice.Country;
using AddonNice.Settings;
using AddonNice.Security;
using AddonNice.CRMWrapper;

namespace AddonNice.Authentication
{
    public class AddonNiceUser : IAddonNiceUser
    {
        /// <summary>
        /// Depending on this mode, ProviderUserKey will contain a real Membership DB key or a Crm Entity(see CrmCustomer for entity type) Key
        /// </summary>
        public AuthenticationMode _UserAuthentication   =   AuthenticationMode.None;
        public AuthenticationMode UserAuthentication
        {
            get { return _UserAuthentication; }
            set { _UserAuthentication = value; }
        }
        
        /// <summary>
        /// In Form Authentication-> Membership user Guid when authenticated or Crm SystemUserId from anonymous impersonating Crm user
        /// In Windows Authentication-> Crm SystemUserId from current user
        /// </summary>
        public Guid _ProviderUserKey                    =   Guid.Empty;
        public Guid ProviderUserKey
        {
            get { return _ProviderUserKey; }
            set { _ProviderUserKey = value; }
        }

        public CrmCustomerId CrmCustomer                =   null;
        public Guid _CrmImpersonateId                   =   Guid.Empty;
        public Guid CrmImpersonateId
        {
            get { return _CrmImpersonateId; }
            set { _CrmImpersonateId = value; }
        }
        public bool _IsAnonymous                        =   true;
        public bool IsAnonymous                         
        {
            get { return _IsAnonymous; }
            set { _IsAnonymous = value; }
        }
        public bool _IsAdmin                             =   false;
        public bool IsAdmin
        {
            get { return _IsAdmin; }
            set { _IsAdmin = value; }
        }
        
		public string CrmCustomerTypeName	
        {
            get
            {
                if ( CrmCustomer != null )
                    return CrmCustomer.typeName;
                return string.Empty;
            }
            set
            {
                if ( CrmCustomer != null )
                    CrmCustomer.typeName = value;
            }
        }

        /// <summary>
        /// CRM Customer Guid
        /// </summary>
		public Guid CrmCustomerCrmId		
        {
            get
            {
                if ( CrmCustomer != null )
                    return CrmCustomer.CrmId;
                return Guid.Empty;
            }
            set
            {
                if ( CrmCustomer != null )
                    CrmCustomer.CrmId = value;
            }
        }

        public DynEntity CrmCustomerGetDynUser(CRMWrapperBase wrapper,ResetWrapperHandler fn)
        {
            if ( CrmCustomer != null )
                return CrmCustomer.GetDynUser(wrapper,fn);
            return null;
        }
        
        /// <summary>
        /// Indicate the nature/validity if the ProviderUserKey
        /// </summary>
        public bool _DummyMembership                     =   true;
        public bool DummyMembership
        {
            get { return _DummyMembership; }
            set { _DummyMembership = value; }
        }
        
        string[] _CRMRoles                              =   null;
    
        CRMWrapperBase wrapper 
        {
            get {  return AddonNice.Security.PortalSecurity.Wrapper;  }
        }

        /// <summary>
        /// Install a recent wrapper in dynEntity
        /// </summary>
        static public void ResetWrapper(DynEntity dyn)
        {
            dyn.SetWrapper(AddonNice.Security.PortalSecurity.Wrapper);
        }

        private PortalSettings _portalSettings;
        public PortalSettings portalSettings
		{
			get
			{
				if(_portalSettings == null)
				{
				    _portalSettings = (PortalSettings) HttpContext.Current.Items[StStr.strPortalSettings];
				}
				return _portalSettings;
			}
		}

        /// <summary>
        /// CRM roles attached to the CRM user attached to the AddonNiceUser (itself or ImpersonateId)
        /// </summary>
        public string[] CRMRoles
        {
            get
            {
                if ( _CRMRoles == null )
                    _CRMRoles   =   wrapper.GetStrUserRoles(CrmImpersonateId);
                return _CRMRoles;
            }
        }

        AddonNiceMembershipUser _AsMembershipUser    =   null;
        public MembershipUser AsMembershipUser
        {
            get
            {
                return _AsMembershipUser;
            }
        }

        /// <summary>
        /// Depending on authentication 
        /// Form->the impersonate user
        /// AD: wrapper.userid
        /// </summary>
        public ADNDynSystemUser GetImpersonateUser(CRMWrapperBase wWrapper)
        {
            ADNDynSystemUser dynUser        =   DynEntity.GetFromCache<ADNDynSystemUser>(CrmStr.systemuser,wWrapper,ResetWrapper,CrmImpersonateId);
            if (portalSettings.AuthMode == AuthenticationMode.Forms)
            {
                return _AsMembershipUser.GetImpersonateUser(wWrapper);
            }
            return DynEntity.GetFromCache<ADNDynSystemUser>(CrmStr.systemuser,wWrapper,ResetWrapper,wWrapper.userId);
        }

        public ADNDynTransactionCurrency DefaultCurrencyID
        {
            get
            {
                Guid TId    =   DefaultCurrencyId;
                if ( TId != Guid.Empty )
                    return DynEntity.GetFromCache<ADNDynTransactionCurrency>(CrmStr.transactioncurrency,wrapper,ResetWrapper,TId);
                return null;
            }
        }

        public Guid DefaultCurrencyId
        {
            get
            {
                ADNDynPricelevel dynPl  =  DefaultPriceList;
                if ( dynPl != null )
                    return dynPl.transactioncurrencyid;
                return Guid.Empty;
            }
        }
        
        public ADNDynPricelevel DefaultPriceList
        {
            get
            {
                Guid PId    =   DefaultPriceListId;
                if ( PId != Guid.Empty )
                    return DynEntity.GetFromCache<ADNDynPricelevel>(CrmStr.pricelevel,wrapper,ResetWrapper,PId);
                return null;
            }
        }

        /// <summary>
        /// Valid if user type is an account or contact, not a Lead or SystemUser 
        /// If no price level, try to take it in the parent customer (only one level)
        /// </summary>
        public virtual Guid DefaultPriceListId
        {
            get
            {
                DynEntity dynUser                   =   CrmCustomer.GetDynUser(wrapper,ResetWrapper);
                switch ( CrmCustomer.typeName )
                {
                    case CrmStr.account:
                    return ( (ADNDynAccount)dynUser).defaultpricelevelid;
                    case CrmStr.contact:
                    Guid prId                       =   ( (ADNDynContact)dynUser).defaultpricelevelid;
                    if ( ( prId == Guid.Empty ) && ( (ADNDynContact)dynUser ).parentcustomerid != Guid.Empty )
                    {
                        switch ( ( (ADNDynContact)dynUser ).parentcustomerName )
                        {
                            case CrmStr.account:
                            ADNDynAccount dynAcc    =   DynEntity.GetFromCache<ADNDynAccount>(CrmStr.account,wrapper,ResetWrapper,( (ADNDynContact)dynUser ).parentcustomerid);
                            return dynAcc.defaultpricelevelid;
                            case CrmStr.contact:
                            ADNDynContact dynCon    =   DynEntity.GetFromCache<ADNDynContact>(CrmStr.contact,wrapper,ResetWrapper,( (ADNDynContact)dynUser ).parentcustomerid);
                            return dynCon.defaultpricelevelid;
                        }
                    }
                    return prId;
                    default:
                    return Guid.Empty;
                }
            }
        }

        /// <summary>
        /// Get current from context
        /// </summary>
        public static AddonNiceUser GetCurrent()
        {
            if ( HttpContext.Current != null )
                return (AddonNiceUser)HttpContext.Current.Items[StStr.CurrentUser];
            return null;
        }

        /// <summary>
        /// Set this object as the current fo the Context
        /// </summary>
        public void SetCurrent()
        {
            if ( HttpContext.Current != null )
                HttpContext.Current.Items[StStr.CurrentUser]    =   this;
        }

        /// <summary>
        ///  When portal authentication is Form:
        ///  - when authenticated take current Membership user
        ///  - else create a new anonymous user based on curent crm wrapper default account (userid)
        ///  When portal authentication is Windows, we are authenticated, take the wrapper userid
        /// </summary>
        public AddonNiceUser()
        {
            if ( SecurityTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddonNiceUser Ctor BEG portalSettings.AuthMode: {0}",portalSettings.AuthMode),SecurityTraceSwitch.Sw.Info);
            try
            {
                if (portalSettings.AuthMode == AuthenticationMode.Forms)
                {
                    UserAuthentication              =    AuthenticationMode.Forms;
                    _AsMembershipUser               =   (AddonNiceMembershipUser)Membership.GetUser();
                    if ( _AsMembershipUser != null )
                    {
                        DummyMembership             =   false;
                        InitFrom(_AsMembershipUser);
                    }
                    else
                    {
                        InitAnonymous(wrapper.userId);
                        DateTime dnow               =   DateTime.Now;
                        DateTime dno                =   new DateTime( 1754, 1, 1 );
                        // Generate a dummy membershipuser not in DB
                        DummyMembership             =   true;
                        _AsMembershipUser           =   new AddonNiceMembershipUser(Membership.Provider.Name,UserName,Guid.Empty,
                                                            CrmCustomer,Email,PasswordQuestion,string.Empty,false,
                                                            false,dnow,dnow,dnow,dno,dno,portalSettings.PortalID,
                                                            portalSettings.BaseAlias,CrmImpersonateId,
                                                            string.Empty,string.Empty,string.Empty,false);
                    }
                }
                else 
                {
                    UserAuthentication              =    AuthenticationMode.Windows;
                    InitFrom(wrapper.userId);
                    // Security
                    IsAdmin                         =   false;
                    DateTime dnow                   =   DateTime.Now;
                    DateTime dno                    =   new DateTime( 1754, 1, 1 );
                    _AsMembershipUser               =   (AddonNiceMembershipUser)Membership.GetUser(UserName,true);
                    if ( _AsMembershipUser != null )
                    {
                        DummyMembership             =   false;
                        ProviderUserKey             =   (Guid)_AsMembershipUser.ProviderUserKey;
                    }
                    else DummyMembership            =   true;

                    if ( SecurityTraceSwitch.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddonNiceUser Ctor _AsMembershipUser: {0}",( _AsMembershipUser != null )),SecurityTraceSwitch.Sw.Info);

                    /*
                    // Generate a dummy membershipuser not in DB
                    _AsMembershipUser               =   new AddonNiceMembershipUser(Membership.Provider.Name,UserName,Guid.Empty,
                                                        CrmCustomer,Email,PasswordQuestion,string.Empty,false,
                                                        false,dnow,dnow,dnow,dno,dno,portalSettings.PortalID,
                                                        portalSettings.BaseAlias,CrmImpersonateId,
                                                        string.Empty,string.Empty,string.Empty,false);
                     */
                 }
            }
            catch (Exception ex)
            {
                if (SecurityTraceSwitch.Sw.TraceError)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]AddonNiceUser Ctor Get ex: {0}", ex), SecurityTraceSwitch.Sw.Info);
                throw;
            }
            if ( SecurityTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddonNiceUser Ctor END Key: [{0}],userName: [{1}], UserAuthentication: {2}",
                     ProviderUserKey, UserName,UserAuthentication),SecurityTraceSwitch.Sw.Info);

        }

        /// <summary>
        /// Init when user accessing from AD 
        /// CrmCustomer  is a CrmCustomerId based on SystemUser and wrapper.userid, 
        /// CrmImpersonateId is wrapper.userid
        /// ProviderUserKey is wrapper UserId-> beware  this is not a real membership DB key
        /// </summary>
        protected virtual void InitFrom(Guid systemUserId)
        {
            if ( SecurityTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddonNiceUser InitFrom BEG systemUserId: {0}",systemUserId),SecurityTraceSwitch.Sw.Info);
            IsAnonymous                 =   false;
            // beware : ProviderUserKey is not a real key in AddoNiceMembership DB-> Potential PB
            ProviderUserKey             =   systemUserId;
            CrmCustomer                 =   new CrmCustomerId(CrmStr.systemuser,systemUserId);
            CrmImpersonateId            =   systemUserId;
            InitWithSystemUser(systemUserId);
        }
        
        protected bool InitWithSystemUser(Guid systemUserId)
        {
            ADNDynSystemUser crmUser        =   DynEntity.GetFromCache<ADNDynSystemUser>(CrmStr.systemuser,wrapper,new ResetWrapperHandler(ResetWrapper),systemUserId);
            if ( crmUser.Retrieved )
            {
                UserName                    =   crmUser.domainname;
                Email                       =   crmUser.internalemailaddress;
                UserFirstName               =   crmUser.firstname;
                nickname                    =   crmUser.nickname;
                BillAddress1                =   crmUser.address1_line1;
                BillAddress2                =   crmUser.address1_line2;
                BillAddress2                =   crmUser.address1_line3;
                BillZip                     =   crmUser.address1_postalcode;
                BillCity                    =   crmUser.address1_city;
                BillCountry                 =   crmUser.address1_country;
                BillCountryID               =   GetCountryID(BillCountry);
                BillCounty                  =   crmUser.address1_county;
                BillCountyID                =   GetCountyID(BillCountry,BillCounty);
                BillPhone                   =   crmUser.address1_telephone1;
                BillFax                     =   crmUser.address1_fax;
            
                ShipAddress1                =   crmUser.address1_line1;
                ShipAddress2                =   crmUser.address1_line2;
                ShipAddress2                =   crmUser.address1_line3;
                ShipZip                     =   crmUser.address1_postalcode;
                ShipCity                    =   crmUser.address1_city;
                ShipCountry                 =   crmUser.address1_country;
                ShipCountryID               =   GetCountryID(ShipCountry);
                ShipCounty                  =   crmUser.address1_county;
                ShipCountyID                =   GetCountyID(ShipCountry,ShipCounty);
                ShipPhone                   =   crmUser.address1_telephone1;
                ShipFax                     =   crmUser.address1_fax;
                UTCConversionTimezone       =   crmUser.utcconversiontimezonecode; // Should ome from usersettings entity
                string CRMAdmin			    =   Config.CRMAdminRole;
                IsAdmin                     =   wrapper.IsInCRMUserRoles(CRMAdmin,systemUserId);
                return true;
            }
            return false;
        }

        /// <summary>
        /// When user is not authenticated CrmCustomer  is a CrmCustomerId based on SystemUser and wrapper.userid, 
        /// CrmImpersonateId is wrapper.userid
        /// ProviderUserKey is Guid.Empty
        /// </summary>
        protected virtual void InitAnonymous(Guid wrapperUserId)
        {
            if ( SecurityTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddonNiceUser InitAnonymous BEG wrapperUserId: {0}",wrapperUserId),SecurityTraceSwitch.Sw.Info);
            IsAnonymous         =   true;
            CrmCustomer         =   new CrmCustomerId(CrmStr.systemuser,wrapperUserId);
            CrmImpersonateId    =   wrapperUserId;
            
            UserName            =   "Anonymous";
            // TODO may be something with Profile when it will work
            //Email               =   HttpContext.Current.Profile...;
            InitWithSystemUser(wrapperUserId);
        }
        
        /// <summary>
        /// Init when accessing with form authentication: CrmCustomer is Membership CustomerId 
        /// and CrmImpersonateId is Membership CrmImpersonateId
        /// ProviderUserKey is Membership value
        /// </summary>
        protected virtual void InitFrom(AddonNiceMembershipUser User)
        {
            if ( SecurityTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddonNiceUser InitFrom BEG AddonNiceMembershipUser: {0}",User.ProviderUserKey),SecurityTraceSwitch.Sw.Info);
            IsAnonymous         =   false;
            ProviderUserKey     =   (Guid)User.ProviderUserKey;
            CrmCustomer         =   User.CustomerId;
            CrmImpersonateId    =   User.CrmImpersonateId;
            
            UserName            =   User.UserName;
            Email               =   User.CrmEMail;
            PasswordQuestion    =   User.PasswordQuestion;
            UserFirstName       =   User.UserFirstName;
            nickname            =   User.nickname;
            Company             =   User.Company;
            Sic                 =   User.SIC;
            BillAddress1        =   User.BillAddress1;
            BillAddress2        =   User.BillAddress2;
            BillAddress3        =   User.BillAddress3;
            BillZip             =   User.BillZip;
            BillCity            =   User.BillCity;
            BillCountry         =   User.BillCountry;
            BillCountryID       =   User.BillCountryID;
            BillCounty          =   User.BillCounty;
            BillCountyID        =   User.BillCountyID;
            BillPhone           =   User.BillPhone;
            BillFax             =   User.BillFax;
        
            ShipAddress1        =   User.ShipAddress1;
            ShipAddress2        =   User.ShipAddress2;
            ShipAddress3        =   User.ShipAddress3;
            ShipZip             =   User.ShipZip;
            ShipCity            =   User.ShipCity;
            ShipCountry         =   User.ShipCountry;
            ShipCountryID       =   User.ShipCountryID;
            ShipCounty          =   User.ShipCounty;
            ShipCountyID        =   User.ShipCountyID;
            ShipPhone           =   User.ShipPhone;
            ShipFax             =   User.ShipFax;
        }
        
        
        string _nickname                    =   string.Empty;
        public string nickname
        {
            get
            {
                return _nickname;
            }
            set
            {
                _nickname = value;
            }
        }
        
        string _UserName = string.Empty;
        public string UserName
        {
            get
            {
                return _UserName;
            }
            set
            {
                _UserName = value;
            }
        }

        string _UserFirstName = string.Empty;
        public string UserFirstName
        {
            get
            {
                return _UserFirstName;
            }
            set
            {
                _UserFirstName = value;
            }
        }

        
        string _Email = string.Empty;
        public string Email
        {
            get
            {
                return _Email;
            }
            set
            {
                _Email = value;
            }
        }

        int _UTCConversionTimezone = 0;
        public int UTCConversionTimezone
        {
            get
            {
                return _UTCConversionTimezone;
            }
            set
            {
                _UTCConversionTimezone = value;
            }
        }

        string _PasswordQuestion = string.Empty;
        public string PasswordQuestion
        {
            get
            {
                return _PasswordQuestion;
            }
            set
            {
                _PasswordQuestion = value;
            }
        }

        bool _SendNewsletter = true;
        public bool SendNewsletter
        {
            get
            {
                return _SendNewsletter;
            }
            set
            {
                _SendNewsletter = value;
            }
        }

        string _Company = string.Empty;
        public string Company
        {
            get
            {
                return _Company;
            }
            set
            {
                _Company = value;
            }
        }

        string _Sic = string.Empty;
        public string Sic
        {
            get
            {
                return _Sic;
            }
            set
            {
                _Sic = value;
            }
        }


        // -------------- for Bill we use address1
        string _BillAddress1 = string.Empty;
        public string BillAddress1
        {
            get
            {
                return _BillAddress1;
            }
            set
            {
                _BillAddress1 = value;
            }
        }
        string _BillAddress2 = string.Empty;
        public string BillAddress2
        {
            get
            {
                return _BillAddress2;
            }
            set
            {
                _BillAddress2 = value;
            }
        }

        string _BillAddress3 = string.Empty;
        public string BillAddress3
        {
            get
            {
                return _BillAddress3;
            }
            set
            {
                _BillAddress3 = value;
            }
        }

        string _BillZip = string.Empty;
        public string BillZip
        {
            get
            {
                return _BillZip;
            }
            set
            {
                _BillZip = value;
            }
        }

        string _BillCity = string.Empty;
        public string BillCity
        {
            get
            {
                return _BillCity;
            }
            set
            {
                _BillCity = value;
            }
        }

        string _BillCountry = string.Empty;
        public string BillCountry
        {
            get
            {
                return _BillCountry;
            }
            set
            {
                _BillCountry = value;
            }
        }


        string _BillCountryID = string.Empty;
        public string BillCountryID
        {
            get
            {
                return _BillCountryID;
            }
            set
            {
                _BillCountryID = value;
            }
        }

        string _BillCounty = string.Empty;
        public string BillCounty
        {
            get
            {
                return _BillCounty;
            }
            set
            {
                _BillCounty = value;
            }
        }


        string _BillCountyID = string.Empty;
        public string BillCountyID
        {
            get
            {
                return _BillCountyID;
            }
            set
            {
                _BillCountyID = value;
            }
        }

        string _BillFax = string.Empty;
        public string BillFax
        {
            get
            {
                return _BillFax;
            }
            set
            {
                _BillFax = value;
            }
        }

        string _BillPhone = string.Empty;
        public string BillPhone
        {
            get
            {
                return _BillPhone;
            }
            set
            {
                _BillPhone = value;
            }
        }

        //-------------- for Ship we use address2
        string _ShipAddress1 = string.Empty;
        public string ShipAddress1
        {
            get
            {
                return _ShipAddress1;
            }
            set
            {
                _ShipAddress1 = value;
            }
        }
        string _ShipAddress2 = string.Empty;
        public string ShipAddress2
        {
            get
            {
                return _ShipAddress2;
            }
            set
            {
                _ShipAddress2 = value;
            }
        }
        string _ShipAddress3 = string.Empty;
        public string ShipAddress3
        {
            get
            {
                return _ShipAddress3;
            }
            set
            {
                _ShipAddress3 = value;
            }
        }

        string _ShipZip = string.Empty;
        public string ShipZip
        {
            get
            {
                return _ShipZip;
            }
            set
            {
                _ShipZip = value;
            }
        }

        string _ShipCity = string.Empty;
        public string ShipCity
        {
            get
            {
                return _ShipCity;
            }
            set
            {
                _ShipCity = value;
            }
        }

        string _ShipCountry = string.Empty;
        public string ShipCountry
        {
            get
            {
                return _ShipCountry;
            }
            set
            {
                _ShipCountry = value;
            }
        }

        string _ShipCountryID = string.Empty;
        public string ShipCountryID
        {
            get
            {
                return _ShipCountryID;
            }
            set
            {
                _ShipCountryID = value;
            }
        }

        string _ShipCounty = string.Empty;
        public string ShipCounty
        {
            get
            {
                return _ShipCounty;
            }
            set
            {
                _ShipCounty = value;
            }
        }

        string _ShipCountyID = string.Empty;
        public string ShipCountyID
        {
            get
            {
                return _ShipCountyID;
            }
            set
            {
                _ShipCountyID = value;
            }
        }

        string _ShipFax = string.Empty;
        public string ShipFax
        {
            get
            {
                return _ShipFax;
            }
            set
            {
                _ShipFax = value;
            }
        }

        string _ShipPhone = string.Empty;
        public string ShipPhone
        {
            get
            {
                return _ShipPhone;
            }
            set
            {
                _ShipPhone = value;
            }
        }

        string _Question = string.Empty;
        public string Question
        {
            get
            {
                return _Question;
            }
            set
            {
                _Question = value;
            }
        }

        string _Answer = string.Empty;
        public string Answer
        {
            get
            {
                return _Answer;
            }
            set
            {
                _Answer = value;
            }
        }

        string _NewPwd = string.Empty;
        public string NewPwd
        {
            get
            {
                return _NewPwd;
            }
            set
            {
                _NewPwd = value;
            }
        }

        public virtual bool hasPassword
        {
            get
            {
                return (portalSettings.AuthMode == AuthenticationMode.Forms);
            }
        }

        public virtual bool hasCompany
        {
            get
            {
                return ( ( portalSettings.AuthMode == AuthenticationMode.Forms) &&
                    ( ((AddonNiceMembershipProvider)Membership.Provider).AutoCreateParentAccount) );
            }
        }
            
        public virtual bool CheckPassword(string password)
        {
            
            if (portalSettings.AuthMode != AuthenticationMode.Forms)
                return false;
            AddonNiceMembershipUser User    =   (AddonNiceMembershipUser)Membership.GetUser();
            return ((AddonNiceMembershipProvider)Membership.Provider).CheckPassword(User.UserName,password,false,true);
        }

        public virtual void Update()
        {
            if ( SecurityTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddonNiceUser Update BEG UserName: {0}, UserAuthentication: {1}",UserName,UserAuthentication),SecurityTraceSwitch.Sw.Info);
            try
            {
                if ( ( UserAuthentication == AuthenticationMode.Forms) ||
                    ( ( UserAuthentication == AuthenticationMode.None ) && (portalSettings.AuthMode == AuthenticationMode.Forms)) )
                {
                    AddonNiceMembershipUser User    =   (AddonNiceMembershipUser)Membership.GetUser();
                    User.CrmEMail                   =   Email;
                    User.UserFirstName              =   UserFirstName;
                    User.nickname                   =   nickname;
                    User.Company                    =   Company;
                    User.SIC                        =   Sic;
                    User.BillAddress1               =   BillAddress1;
                    User.BillAddress2               =   BillAddress2;
                    User.BillAddress3               =   BillAddress3;
                    User.BillZip                    =   BillZip;
                    User.BillCity                   =   BillCity;
                    User.BillCountry                =   BillCountry;
                    User.BillCounty                 =   BillCounty;
                    User.BillPhone                  =   BillPhone;
                    User.BillFax                    =   BillFax;
                    User.ShipAddress1               =   ShipAddress1;
                    User.ShipAddress2               =   ShipAddress2;
                    User.ShipAddress3               =   ShipAddress3;
                    User.ShipZip                    =   ShipZip;
                    User.ShipCity                   =   ShipCity;
                    User.ShipCountry                =   ShipCountry;
                    User.ShipCounty                 =   ShipCounty;
                    User.ShipPhone                  =   ShipPhone;
                    User.ShipFax                    =   ShipFax;
                    User.SetNewQuestion(Question);
                    User.SetNewAnswer(Answer);
                    User.SetNewPwd(NewPwd);  
                    User.UpdateCrmData();
                }
                else // windows authentication (AD)
                {
                    ADNDynSystemUser crmUser        =   new ADNDynSystemUser(wrapper, ProviderUserKey);
                    crmUser.systemuserid            =   ProviderUserKey;
                    crmUser.lastname                =   UserName;
                    crmUser.internalemailaddress    =   Email;
                    crmUser.firstname               =   UserFirstName;
                    crmUser.nickname                =   nickname;
                    crmUser.address1_line1          =   BillAddress1;
                    crmUser.address1_line2          =   BillAddress2;
                    crmUser.address1_line3          =   BillAddress2;
                    crmUser.address1_postalcode     =   BillZip;
                    crmUser.address1_city           =   BillCity;
                    crmUser.address1_country        =   BillCountry;
                    crmUser.address1_county         =   BillCounty;
                    crmUser.address1_telephone1     =   BillPhone;
                    crmUser.address1_fax            =   BillFax;

                    crmUser.address1_line1          =   ShipAddress1;
                    crmUser.address1_line2          =   ShipAddress2;
                    crmUser.address1_line3          =   ShipAddress2;
                    crmUser.address1_postalcode     =   ShipZip;
                    crmUser.address1_city           =   ShipCity;
                    crmUser.address1_country        =   ShipCountry;
                    crmUser.address1_county         =   ShipCounty;
                    crmUser.address1_telephone1     =   ShipPhone;
                    crmUser.address1_fax            =   ShipFax;

                    crmUser.Update();
                }
                if ( SecurityTraceSwitch.Sw.TraceVerbose )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddonNiceUser Update END UserName: {0}, UserAuthentication: {1}",UserName,UserAuthentication),SecurityTraceSwitch.Sw.Info);
            }
            catch (Exception ex)
            {
                if (SecurityTraceSwitch.Sw.TraceError)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]AddonNiceUser update ex: {0}", ex), SecurityTraceSwitch.Sw.Info);
                throw;
            }
        }

        public string GetCountryID(string CountryName)
        {
            if (!string.IsNullOrEmpty(CountryName))
            {
                try
                {
                    CountryInfo country     =   new CountryInfo(CountryName);
                    if (SecurityTraceSwitch.Sw.TraceVerbose)
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddonNiceUser GetCountryID CountryName: {0}, CountryID: {1}",
                            CountryName, country.ThreeLetterISOCountryName), SecurityTraceSwitch.Sw.Info);
                    return country.ThreeLetterISOCountryName;
                }
                catch (Exception ex)
                {
                    if (SecurityTraceSwitch.Sw.TraceError)
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]AddonNiceUser GetCountryID CountryName: {0}, ex: {1}", CountryName, ex), SecurityTraceSwitch.Sw.Info);
                }
            }
            if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddonNiceUser GetCountryID NOT FOUND CountryName: {0}", CountryName), SecurityTraceSwitch.Sw.Info);
            return string.Empty;
        }

        public string GetCountyID(string CountryName, string CountyName)
        {
            if (!string.IsNullOrEmpty(CountryName))
            {
                try
                {
                    CountryInfo country =   new CountryInfo(CountryName);
                    CountryInfo county  =   country.GetChildCountryInfo(CountyName);
                    if (SecurityTraceSwitch.Sw.TraceVerbose)
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddonNiceUser GetCountyID CountryName: {0}, CountyName: {1}, county: {2}", 
                            CountryName, CountyName, county != null), SecurityTraceSwitch.Sw.Info);
                    if ( county != null )
                        return county.EnglishName;
                }
                catch (Exception ex)
                {
                    if (SecurityTraceSwitch.Sw.TraceError)
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]AddonNiceUser GetCountyID CountryName: {0}, CountyName: {1}, ex: {2}",
                            CountryName, CountyName, ex), SecurityTraceSwitch.Sw.Info);
                }
            }
            if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddonNiceUser GetCountyID NOT FOUND CountryName: {0}, CountyName: {1}", CountryName, CountyName), SecurityTraceSwitch.Sw.Info);
            return string.Empty;
        }
    
    }
}
